<template>
  <div class="modal" v-show="$store.state.isOpenLogin">
    <!-- 点击空白关闭登录框 -->
    <div class="modal_bg" @click="closeLogin"></div>
    <div class="modal_content">
      <!-- 点击X关闭登录框 -->
      <img
        class="close"
        @click="closeLogin"
        src="../assets/images/login/userArrow.png"
        alt=""
      />
      <!-- 头部 -->
      <section>
        <span :class="{ active: showPhone }" @click="showPhone = true">手机号登录</span>
        <span :class="{ active: !showPhone }" @click="wechatLoginFn">微信扫码登录</span>
      </section>

      <!-- 手机号登录部分 -->
      <div class="phone_login" v-show="showPhone">
        <div class="line tanxin">
          <input type="text" placeholder="请输入手机号" v-model="phone" />
        </div>
        <div class="verify_box">
          <slide-verify
            :l="42"
            :r="20"
            :w="360"
            :h="140"
            :slider-text="msg"
            @success="onSuccess"
            @fail="onFail"
            @refresh="onRefresh"
            :style="{ width: '100%' }"
            class="slide-box"
            ref="slideBlock"
          >
          </slide-verify>
          <div>{{ msg }}</div>
        </div>
        <div class="line tanxin">
          <input type="text" placeholder="请输入短息验证码" v-model="code" />
          <div class="btn" @click="getCodeFn" v-if="codeStatus">获取验证码</div>
          <div class="code" v-else>{{ time }}s</div>
        </div>
        <div class="btn_login" @click="submitFn">登录</div>
      </div>
      <!-- 微信扫码登录部分 -->
      <div id="weixin" v-show="!showPhone"></div>
    </div>
  </div>
</template>

<script>
import { BindWechatApi, getCodeApi, LoginApi } from "@/request/api";
const validatephone = (phone) => {
  let reg =
    /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
  // 手机号正确 返回true  错误 返回false
  return reg.test(phone.trim());
};
export default {
  data() {
    return {
      // true 表示显示手机号登录，false 表示显示微信
      showPhone: true,
      // 手机号
      phone: "13035633132",
      // 验证码
      code: "",
      msg: "向右滑动",
      // 倒计时
      time: 10,
      // 获取验证码状态，true代表要显示 "获取验证码"，false代表显示 "倒计时"
      codeStatus: true,
    };
  },
  methods: {
    // 切换到微信登录
    wechatLoginFn() {
      this.showPhone = false;
      let _this = this;
      console.log(process.env.VUE_APP_STATE_URL + _this.$route.path);
      new WxLogin({
          id: "weixin",
          appid: "wx67cfaf9e3ad31a0d",  // 这个appid要填死
          scope: "snsapi_login",
          // 扫码成功后重定向的接口
          redirect_uri: "https://sc.wolfcode.cn/cms/wechatUsers/shop/PC",
          // state填写编码后的url
          state: encodeURIComponent(
            window.btoa(process.env.VUE_APP_STATE_URL + _this.$route.path)
          ),
          // 调用样式文件
          href: "data:text/css;base64,Lyogd3hsb2dpbi5jc3MgKi8NCi5pbXBvd2VyQm94IC50aXRsZSwgLmltcG93ZXJCb3ggLmluZm97DQogICAgZGlzcGxheTogbm9uZTsNCn0NCg0KLmltcG93ZXJCb3ggLnFyY29kZXsNCiAgICBtYXJnaW4tdG9wOiAxMHB4Ow0KfQ0K",
      });
    },
    // 关闭这个登录框
    closeLogin() {
      this.$store.commit("changeLoginShow", false);
    },
    // 拼图成功的时候
    onSuccess(times) {
      let ms = (times / 1000).toFixed(1);
      this.msg = "快如闪电, 耗时 " + ms + "s";
      // this.msg = `快如闪电, 耗时${(times / 1000).toFixed(1)}s`;
    },
    // 拼图失败的时候
    onFail() {
      this.msg = "失败";
    },
    // 拼图刷新的时候
    onRefresh() {
      this.msg = "再试一次";
    },
    // 点击登录按钮
    submitFn() {
      // 验证手机格式是否正确
      let result = validatephone(this.phone);
      if (!result) {
        // 检验手机号错误的时候
        let obj = { content: "请输入验证码", icon: "danger" };
        this.$store.dispatch("AsyncToast", obj);
        return;
      }
      // 校验验证码是否填写
      let mycode = this.code.trim();
      if (mycode == "") {
        let obj = { content: "请输入验证码", icon: "danger" };
        this.$store.dispatch("AsyncToast", obj);
        return;
      }
      // 校验滑块是否滑动
      if (
        this.msg == "再试一次" ||
        this.msg == "失败" ||
        this.msg == "向右滑动"
      ) {
        let obj = { content: "请完成拼图", icon: "danger" };
        this.$store.dispatch("AsyncToast", obj);
        return;
      }

      // 以上的条件如果都成立 ， 就可以开始登录

      // 存在uuid
      let uuid = sessionStorage.getItem("uuid");
      if(uuid) {
        // 证明此时是从微信扫码后想要做的手机号登录
        BindWechatApi({
          phone: this.phone,
          verifyCode: this.code,
          uuid: this.uuid
        }).then((res) => {
          // 存储token
          localStorage.setItem("x-auth-token", res.data["x-auth-token"]);
          // localStorage.setItem("x-auth-token", 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2NjQzNDY4ODEsImlhdCI6MTY2Mzc0MjA4MSwidXNlcm5hbWUiOiIzMGY5MTRjNy03M2FhLTQ3OWUifQ.iW1zZNVRtdmaM5w7XXbaojkPR0YaTcpBZPBTByMUJDQ');
          // 提示成功
          let obj = { content: "登录成功", icon: "success" };
          this.$store.dispatch("AsyncToast", obj);
          // 关闭登录框
          this.$store.commit("changeLoginShow", false);
          // 更新header组件
          this.$emit("updateKeyFn"); 
          // 删除地址栏的code
          this.$router.push(this.$route.path);
          // 删除uuid
          sessionStorage.removeItem('uuid');
        })
      } else {
        LoginApi({
          verifyCode: this.code,
          phone: this.phone,
        }).then((res) => {
          if (res.data.code === 0) {
            // 存储token
            localStorage.setItem("x-auth-token", res.data["x-auth-token"]);
            // localStorage.setItem("x-auth-token", 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2NjQzNDY4ODEsImlhdCI6MTY2Mzc0MjA4MSwidXNlcm5hbWUiOiIzMGY5MTRjNy03M2FhLTQ3OWUifQ.iW1zZNVRtdmaM5w7XXbaojkPR0YaTcpBZPBTByMUJDQ');
            // 提示成功
            let obj = { content: "登录成功", icon: "success" };
            this.$store.dispatch("AsyncToast", obj);
            // 关闭登录框
            this.$store.commit("changeLoginShow", false);
            // 更新header组件
            this.$emit("updateKeyFn"); 
            // 删除地址栏的code
            this.$router.push(this.$route.path);
            // 删除uuid
            sessionStorage.removeItem('uuid')
          }
        });
      }
    },
    // 获取验证码
    getCodeFn() {
      // 验证手机格式是否正确
      let result = validatephone(this.phone);
      if (!result) {
        // 检验手机号错误的时候
        let obj = { content: "请重新输入手机号", icon: "danger" };
        this.$store.dispatch("AsyncToast", obj);
        return;
      }
      // 校验滑块是否滑动
      if (
        this.msg == "再试一次" ||
        this.msg == "失败" ||
        this.msg == "向右滑动"
      ) {
        let obj = { content: "请完成拼图", icon: "danger" };
        this.$store.dispatch("AsyncToast", obj);
        return;
      }
      // 如果手机号、校验滑块都没问题，就继续正常往下走
      // 获取验证码 --> 倒计时功能
      getCodeApi({
        phone: this.phone,
      }).then((res) => {
        if (res.data.code === 0) {
          // 成功发送验证码
          let obj = { content: "发送验证码成功", icon: "success" };
          this.$store.dispatch("AsyncToast", obj);
          this.codeStatus = false; // 显示倒计时
          let timer = setInterval(() => {
            this.time--;
            if (this.time === 0) {
              clearInterval(timer); // 终止定时器
              this.time = 10; // 初始化数字
              this.codeStatus = true; // 显示"获取验证码"按钮
            }
          }, 1000);
        } else {
          // 发送验证码失败
          let obj = { content: "发送验证码失败", icon: "danger" };
          this.$store.dispatch("AsyncToast", obj);
        }
      });
    },
  },
};
</script>
 
<style lang = "less" scoped>
@import "../assets/base.less";
.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;

  .modal_bg {
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
  }

  .modal_content {
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    margin: auto;
    width: 555px;
    height: 423px;
    background-image: url(../assets/images/login/loginBg.png);
    .close {
      position: absolute;
      right: 60px;
      top: 15px;
      cursor: pointer;
    }
    section {
      display: flex;
      justify-content: center;
      margin-top: 40px;
      margin-bottom: 30px;
      span {
        color: #ccc;
        cursor: pointer;
        &:nth-of-type(1) {
          border-right: 1px solid #ccc;
          padding-right: 10px;
          margin-right: 10px;
        }
        &.active {
          color: @black;
        }
      }
    }
    .line {
      width: 360px;
      margin: 0 auto 20px;
      height: 50px;
      input {
        flex: 1;
        text-indent: 1em;
        outline: none;
      }
      .btn {
        color: #fff;
        background-color: @blue;
        text-align: center;
        width: 90px;
        height: 50px;
        cursor: pointer;
        margin-left: 10px;
        line-height: 50px;
      }
      .code {
        color: @black;
        background-color: #ccc;
        text-align: center;
        width: 90px;
        height: 50px;
        cursor: pointer;
        margin-left: 10px;
        line-height: 50px;
      }
    }
    .btn_login {
      width: 360px;
      height: 50px;
      background-color: @blue;
      color: #fff;
      line-height: 50px;
      margin: auto;
      text-align: center;
      cursor: pointer;
    }
  }
  .verify_box {
    width: 360px;
    margin: 0 auto 20px;
    /deep/.slide-box {
      width: 100%;
      position: relative;
      box-sizing: border-box;
      canvas {
        position: absolute;
        left: 0;
        top: -140px;
        display: none;
        width: 100%;
        box-sizing: border-box;
      }
      .slide-verify-block {
        width: 85px;
        height: 136px;
      }
      .slide-verify-refresh-icon {
        top: -140px;
        display: none;
      }
      &:hover {
        canvas {
          display: block;
        }
        .slide-verify-refresh-icon {
          display: block;
        }
      }
    }
  }
  #weixin {
    text-align: center;
  }
}
</style>